package org.jcms.web.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jcms.model.Manager;
import org.jcms.service.ManagerServiceI;
import org.jcms.uitils.MD5;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class StorehouseChangePersonalInfomation extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public StorehouseChangePersonalInfomation() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		ApplicationContext ac = WebApplicationContextUtils
				.getRequiredWebApplicationContext(this.getServletContext());
		ManagerServiceI managerServiceI = (ManagerServiceI) ac
				.getBean("managerServiceImpl");

		String managerID = request.getParameter("managerID");
		String oldPsd = request.getParameter("OldPsd");
		String newPsd = request.getParameter("NewPsd");
		String uname = request.getParameter("Uname");

		String retJson = "{\"error\":@err,\"msg\":\"@msg\"}";
		String err = "1";
		String msg = "";

		try {

			Manager manager = managerServiceI.findById(managerID);

			if (manager == null) {

				msg = "此用户不存在";
				return;
			}

			if (!manager.getManagerPassword().equals(MD5.md5s(oldPsd))) {

				msg = "旧密码错误";
				return;
			}
			manager.setManagerName(uname);
			if (!(newPsd == null || newPsd.equals(""))) {
				manager.setManagerPassword(MD5.md5s(newPsd));
			}

			managerServiceI.update(manager);

			err = "0";
			msg = "修改成功";
			Manager sessManager = (Manager) request.getSession().getAttribute(
					"manager-1");

			if (sessManager != null
					&& sessManager.getManagerId()
							.equals(manager.getManagerId())) {

				request.getSession().setAttribute("manager-1", manager);
			}

		}

		catch (Exception e) {
			e.printStackTrace();
			msg = "系统错误";
		}

		finally {
			retJson = retJson.replace("@err", err);
			retJson = retJson.replace("@msg", msg);
			response.getOutputStream().write(retJson.getBytes("utf-8"));
		}
	}

	public void init() throws ServletException {
		// Put your code here
	}

}
